<template>
  <div class="">
    <UploadExcel :on-success="success" />
  </div>
</template>

<script>
import { improtEmployee } from '@/api/employees'
export default {
  name: 'Improt',
  components: {},
  props: {},
  data() {
    return {
    }
  },
  computed: {},
  watch: {},
  created() { },
  mounted() { },
  methods: {
    async success({ header, results }) {
      // results获得的数据key：value 的key为中文这里需要转成英文
      const userRelations = {
        // 对应关系列表
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber'
      }
      // results.forEach(item => {
      //   const userInfo = {}
      // // Object.keys 获取的可枚举属性名
      //   Object.keys(item).forEach(key => {
      //     userInfo[userRelations[key]] = item[key]
      //   })
      // })
      const newArray = results.map(item => {
        const userInfo = {}
        Object.keys(item).forEach(key => {
          // key为item对象中的中文属性
          if (userRelations[key] === 'timeOfEntry' || userRelations[key] === 'correctionTime') {
            userInfo[userRelations[key]] = new Date(this.formatDate(item[key], '/'))
          } else {
            userInfo[userRelations[key]] = item[key]
          }
        })
        return userInfo
      })
      await improtEmployee(newArray)
      this.$message.success('导入数据成功')
      this.$router.back()
    },
    // excel表格时间转换
    formatDate(numb, format) {
      const time = new Date((numb - 1) * 24 * 3600000 + 1)
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() - 1 + ''
      if (format && format.length === 1) {
        return year + format + month + format + date
      }
      return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
    }
  }
}
</script>

<style lang="less" scoped></style>
